/*
 * MyTableModel.java
 *
 * Created on 2 de octubre de 2005, 04:04 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ig.formato.util;

//import com.hxtt.swing.util.TableSorter;
import ig.formato.dto.TipoRegistroDTO;
import java.util.ArrayList;
import java.util.Collection;
//import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import javax.swing.table.AbstractTableModel;
//import javax.swing.table.JTableHeader;

public class TableModelTR extends AbstractTableModel {

        private boolean DEBUG = false;
        private boolean[] editables = null;
        private String[] estado = null;
        private String[] estadoAnterior = null;
        private Object[][] object;
        private String[] columnNames = null;
        private Object[][] data = null;
        private boolean delFisico = false;
        private Integer[] columnasDiferentes = new Integer[0];
        private Collection<TipoRegistroDTO> cEliminados = new ArrayList<TipoRegistroDTO>();

        public TableModelTR(Object[][] object, String[] columnNames, boolean[] editables,Integer[] columnasDiferentes) {
            this.editables = editables;
            this.columnNames = columnNames;
            this.columnasDiferentes=columnasDiferentes;
            if (object != null) {
                this.object = object;
            } else {
                this.object = new Object[0][columnNames.length];
            }
            setData(this.object);
        }

        public boolean isDelFisico() {
            return delFisico;
        }

        public String[] getEstado() {
            return estado;
        }

        public void setData(Object[][] _data) {
            if (_data != null) {
                data = new Object[_data.length][columnNames.length];
                for (int j = 0; j < columnNames.length; j++) {
                    for (int i = 0; i < _data.length; i++) {
                        this.data[i][j] = _data[i][j];
                    }
                }
                this.fireTableDataChanged();
            } else {
                this.object = new Object[0][columnNames.length];
                this.data = new Object[0][columnNames.length];
                this.ht.clear();
            }            
        }

        private void copyEstadosNuevos() {
            estadoAnterior = new String[estado.length];
            for (int i = 0; i < estado.length; i++) {
                estadoAnterior[i] = estado[i];
            }
        }

        private void copyEstadosViejos() {
            for (int i = 0; i < estadoAnterior.length; i++) {
                estado[i] = estadoAnterior[i];
            }
            copyEstadosNuevos();
        }

        //super.addTableModelListener()
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            if (editables[col] == true) {
                return true;
            } else {
                return false;
            }
        }

        public Object[][] getData() {
            return this.data;
        }

        public Object[][] getObjet() {
            return this.object;
        }

        public void setValueAt(Object value, int row, int col) {

            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
                System.out.println("New value of data:");
                printDebugData();
            }
            boolean existe = false;
            for (int i = 0; i < columnasDiferentes.length; i++) {
                if ((columnasDiferentes[i].intValue() - 1) == col) {
                    for (int j = 0; j < data.length; j++) {
                        if (data[j][col].toString().trim().equals(value.toString().trim()) && j != row) {
                            existe = true;
                            break;
                        }
                    }
                }
                if (existe) {
                    break;
                }
            }

            if (existe) {
                data[row][col] = "<Tipo Existente>";
            } else {
                data[row][col] = value;
                if (col == 0) {
                    this.getHt().get(row).setOrden(row);
                    this.getHt().get(row).setTipoRegistro(Integer.valueOf(value.toString().trim()));
                }
                if (col == 1) {
                    this.getHt().get(row).setActivo((Boolean) value ? 1 : 0);
                }
                if (col == 2) {
                    this.getHt().get(row).setRequerido((Boolean) value ? 1 : 0);
                }                
            }
            setData(data);
            this.fireTableDataChanged();
        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i = 0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j = 0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
        }

        public synchronized void moverArriba(int row) {
            Object[][] data_1 = new Object[this.data.length][this.getColumnCount()];
            for (int i = 0; i < data_1.length; i++) {
                for (int j = 0; j < this.getColumnCount(); j++) {
                    data_1[i][j] = data[i][j];
                }
            }
            for (int i = 0; i < data_1.length; i++) {
                if (i == row) {
                    for (int j = 0; j < this.getColumnCount(); j++) {
                        this.data[i - 1][j] = data_1[i][j];
                    }
                    for (int j = 0; j < this.getColumnCount(); j++) {
                        this.data[i][j] = data_1[i - 1][j];
                    }
                    ig.formato.dto.TipoRegistroDTO obj = getHt().get(row);
                    ig.formato.dto.TipoRegistroDTO obj1 = getHt().get(row - 1);
                    obj1.Relaciones().remove(obj.getId());
                    obj1.setOrden(row);
                    getHt().put(row, obj1);

                    obj.setOrden(row - 1);
                    getHt().put(row - 1, obj);
                    break;
                }
            }
            this.fireTableDataChanged();
        }

        public synchronized void moverAbajo(int row) {
            Object[][] data_1 = new Object[this.data.length][this.getColumnCount()];
            for (int i = 0; i < data_1.length; i++) {
                for (int j = 0; j < this.getColumnCount(); j++) {
                    data_1[i][j] = data[i][j];
                }
            }
            for (int i = 0; i < data_1.length; i++) {
                if (i == row) {
                    for (int j = 0; j < this.getColumnCount(); j++) {
                        this.data[i + 1][j] = data_1[i][j];
                    }
                    for (int j = 0; j < this.getColumnCount(); j++) {
                        this.data[i][j] = data_1[i + 1][j];
                    }
                    ig.formato.dto.TipoRegistroDTO obj = getHt().get(row);
                    ig.formato.dto.TipoRegistroDTO obj1 = getHt().get(row + 1);
                    obj1.Relaciones().remove(obj.getId());
                    obj1.setOrden(row);
                    getHt().put(row, obj1);

                    obj.setOrden(row + 1);
                    getHt().put(row + 1, obj);
                    break;
                }
            }
            this.fireTableDataChanged();
        }
        private java.util.Hashtable<Integer, ig.formato.dto.TipoRegistroDTO> ht = new java.util.Hashtable<Integer, ig.formato.dto.TipoRegistroDTO>();
        int id=-1;
        public synchronized void nuevo() {
            Object[][] data_1 = new Object[this.data.length + 1][this.getColumnCount()];
            ig.formato.dto.TipoRegistroDTO tr = new ig.formato.dto.TipoRegistroDTO();
            
            Properties pro=LoadProperties.loadPropertiess("conf/tr.properties");
            String longitud=pro.getProperty("longitud");
            String muestras=pro.getProperty("muestras");
            String separador=pro.getProperty("separador");
            tr.setLongitud(longitud!=null && !longitud.trim().equals("")?longitud:"0");
            tr.setMuestras(muestras!=null && !muestras.trim().equals("")?Integer.valueOf(muestras):0);
            tr.setSeparadorCampo(separador!=null && !separador.trim().equals("")?separador:"");
            tr.setActivo(0);
            tr.setRequerido(0);
            tr.setId(id--);
            int tipo = 1;
            boolean seguir = true;
            while (seguir) {
                seguir = false;
                for (int i = 0; i < data.length; i++) {
                    if (Integer.valueOf(data[i][0].toString()).intValue() == tipo) {
                        tipo++;
                        seguir = true;
                        break;
                    }
                }
            }
            tr.setTipoRegistro(tipo);
            for (int i = 0; i < data_1.length; i++) {
                for (int j = 0; j < this.getColumnCount(); j++) {
                    try {
                        data_1[i][j] = data[i][j];
                    } catch (Exception e) {
                        tr.setOrden(i);
                        if (j == 0) {
                            data_1[i][j] = tr.toString();
                        } else if (j == 1) {
                            data_1[i][j] = tr.getActivo().equals(1) ? true : false;
                        }else{
                            data_1[i][j] = tr.getRequerido().equals(1) ? true : false;
                        }
                    }
                }
            }
            this.data = data_1;
            getHt().put(tr.getOrden(), tr);
            this.fireTableDataChanged();
        }

        public synchronized void eliminar(int row) {
            Object[][] data_1 = new Object[this.data.length - 1][this.getColumnCount()];
            int x = -1;
            for (int i = 0; i < data.length; i++) {
                if (i != row) {
                    x++;
                }
                for (int j = 0; j < this.getColumnCount(); j++) {
                    if (i != row) {
                        data_1[x][j] = data[i][j];
                    }
                }
            }
            this.data = data_1;
            ig.formato.dto.TipoRegistroDTO dtoDel = getHt().get(row);
            if (dtoDel.getId() != null) {
                this.cEliminados.add(dtoDel);
            }
            getHt().remove(row);
            java.util.Hashtable<Integer, ig.formato.dto.TipoRegistroDTO> newHt = new java.util.Hashtable<Integer, ig.formato.dto.TipoRegistroDTO>();
            boolean okNull = false;
            for (int i = 0; i < ht.size(); i++) {
                ig.formato.dto.TipoRegistroDTO dto = ht.get(i);
                if (dto != null && !okNull) {
                    newHt.put(dto.getOrden(), dto);
                } else {
                    okNull = true;
                    dto = ht.get(i + 1);
                    dto.setOrden(i);
                    newHt.put(dto.getOrden(), dto);
                }
//                System.out.println(newHt.get(i).getOrden()+" - "+newHt.get(i).getTipoRegistro());
            }
            this.ht = newHt;
            this.fireTableDataChanged();
        }

        public Integer[] getColumnasDiferentes() {
            return columnasDiferentes;
        }

        public void setColumnasDiferentes(Integer[] columnasDiferentes) {
            this.columnasDiferentes = columnasDiferentes;
        }

        public java.util.Hashtable<Integer, ig.formato.dto.TipoRegistroDTO> getHt() {
            return ht;
        }

        public void setHt(java.util.Hashtable<Integer, ig.formato.dto.TipoRegistroDTO> ht) {
            this.ht = ht;
            this.data = new Object[ht.size()][3];
            int key = 0;
            int size = 0;
            int row = 0;
            while (true) {
                TipoRegistroDTO tipoRegistroDTO = ht.get(key++);
                if (tipoRegistroDTO != null) {
                    size++;
                    this.data[row][0] = tipoRegistroDTO.toString();
                    this.data[row][1] = tipoRegistroDTO.getActivo().equals(1) ? true : false;
                    this.data[row++][2] = tipoRegistroDTO.getRequerido().equals(1) ? true : false;
                }
                if (size >= ht.size()) {
                    break;
                }
            }
            this.fireTableDataChanged();
        }
        /***
         * 
         */
        public Object[][] getDataExcluir(int row) {
            Hashtable<Integer,Object[][]> _ht=new  Hashtable<Integer,Object[][]>();
            int ii = 0;
            for (int i = 0; i < data.length; i++) {
                if (i!=row && ht.get(row).getOrden()<ht.get(i).getOrden() && !this.tienePadre(ht.get(i).getId(),row)/*.Relaciones().size()<=0/*get(ht.get(row).getId())==null*/){
                    Object[][] dataEx1=new Object[1][2];
                    for (int j = 0; j < columnNames.length; j++) {
                        if(j==1){
                            dataEx1[0][1]= ht.get(row).Relaciones().get(ht.get(i).getId())==null?false:true;
                        }else if(j==0){
                            dataEx1[0][0]= ht.get(i);
                        }
                    }
                    _ht.put(ii, dataEx1);
                    ii++;
                }
            }
            Object[][] dataEx = new Object[_ht.size()][2];
            Integer key=0;
            while(_ht.get(key)!=null){
                dataEx[key][0]=_ht.get(key)[0][0];
                dataEx[key][1]=_ht.get(key)[0][1];
                key++;
            }
            return dataEx;
        }

        private boolean tienePadre(Integer id,int row){
            for (int i = 0; i < data.length; i++) {
                if(ht.get(i).Relaciones().get(id)!=null && i!=row)
                    return true;
            }
            return false;
        }
        public Collection<TipoRegistroDTO> getCEliminados() {
            return cEliminados;
        }
    }
